<?php

namespace App\Services;

use App\Libraries\CUOss;
use App\Libraries\MicrosoftSpeech;
use App\Models\Book;
use App\Models\Chapter;
use App\Models\MicrosoftVoice;
use App\Models\MicrosoftVoicesStyle;
use Exception;
use Illuminate\Support\Facades\Storage;

class AudioBookService
{
    public function getVoices()
    {
        $list = (new MicrosoftSpeech())->getVoices();
        foreach ($list as $item) {
            if (!in_array($item['Locale'], ['en-US'])) {
                continue;
            }
            $microsoftVoice = MicrosoftVoice::firstOrCreate(
                ['display_name' => $item['DisplayName'], 'gender' => $item['Gender'], 'locale' => $item['Locale']],
                [
                    'name' => $item['Name'],
                    'local_name' => $item['LocalName'],
                    'short_name' => $item['ShortName'],
                    'locale_name' => $item['LocaleName'],
                    'voice_type' => $item['VoiceType'],
                    'status' => $item['Status'],
                    'style_count' => isset($item['StyleList']) ? count($item['StyleList']) : 0
                ]
            );

            if (!empty($microsoftVoice) && isset($item['StyleList'])) {
                foreach ($item['StyleList'] as $style) {
                    MicrosoftVoicesStyle::firstOrCreate(
                        ['voices_id' => $microsoftVoice->id, 'style' => $style]
                    );
                }
            }
        }
    }
    public function importBook($book_id)
    {
        $book = Book::find($book_id);
        if (empty($book)) {
            throw new Exception('参数错误');
        }

        if (empty($book->output_url)) {
            throw new Exception('文件未下载');
        }

        $file_name = pathinfo($book->output_url, PATHINFO_BASENAME);
        $CUOss = new CUOss('novel');
        $file_url = $CUOss->urlAuth($book->output_url);

        // 下载文件到本地
        $file_path = dowload_file($file_url, $file_name);
        if (!file_exists($file_path)) {
            throw new Exception('文件不存在');
        }

        // 打开文件
        $file = fopen($file_path, "r");
        if (!$file) {
            throw new Exception('无法打开文件');
        }

        // 初始化一个变量来存储每部的内容
        $current_part = [];
        $parts = [];

        // 正则表达式模式，用于匹配部标题
        $pattern = '/(第[一二三四五六七八九十百千万零]+部) ([^\n]*)/';
        // 逐行读取文件
        while (($line = fgets($file)) !== false) {
            // 去除行首尾的空白字符
            $line = trim($line);
            if (empty($line)) {
                continue;
            }
            // 检查是否匹配部标题
            if (preg_match($pattern, $line, $matches)) {
                // 如果当前部分不为空，则将其存储到部分数组中
                if (!empty($current_part)) {
                    $parts[] = $current_part;
                    $current_part = [];
                }
            }
            // 将当前行添加到当前部分
            $current_part[] = $line;
        }
        // 将最后一部分添加到部分数组中
        if (!empty($current_part)) {
            $parts[] = $current_part;
        }

        // 关闭文件
        fclose($file);
        // 输出每部分的标题
        $chapters = [];
        foreach ($parts as $part) {
            // 获取并打印标题
            $part_content = implode("\n", $part);
            $pattern = '/(第[一二三四五六七八九十百千万零0-9]+部) ([^\n]*)/';
            $part_name = '';
            if (preg_match($pattern, $part_content, $matches)) {
                $part_name = $matches[0];
            }
            $pattern = '/(第[一二三四五六七八九十百千万零0-9]+章) ([^\n]*)/';
            if (preg_match($pattern, $part_content, $matches)) {
                $part_content = substr($part_content, stripos($part_content, $matches[0]));
                $sections = preg_split($pattern, $part_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
                for ($i = 0; $i < count($sections); $i += 3) {
                    $chapter_name = $sections[$i] . ' ' . $sections[$i + 1];
                    $chapter_content = $sections[$i + 2];
                    $chapter_content = ltrim(str_replace("\u{3000}\u{3000}", "", $chapter_content), "\n");
                    $count_words = count_words($chapter_content);

                    $chapters[] = [
                        'part_name' => trim($part_name),
                        'name' => trim($chapter_name),
                        'original_content' => trim($chapter_content),
                        'original_count_words' => $count_words
                    ];
                }
            } else {
                $pattern = '/(第[一二三四五六七八九十百千万零0-9]+章)/';
                if (preg_match($pattern, $part_content, $matches)) {
                    $part_content = substr($part_content, stripos($part_content, $matches[0]));
                    $sections = preg_split($pattern, $part_content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
                    for ($i = 0; $i < count($sections); $i++) {
                        if (preg_match($pattern, $sections[$i])) {
                            // 是章节标题，创建一个新的章节
                            $chapter_name = $sections[$i];
                            $chapter_content = isset($sections[$i + 1]) ? trim($sections[$i + 1]) : '';
                            $chapter_content = ltrim(str_replace("\u{3000}\u{3000}", "", $chapter_content), "\n");
                            $count_words = count_words($chapter_content);

                            $chapters[] = [
                                'part_name' => trim($part_name),
                                'name' => trim($chapter_name),
                                'original_content' => trim($chapter_content),
                                'original_count_words' => $count_words
                            ];
                        }
                    }
                }
            }
        }

        Chapter::where('book_id', $book_id)->update(['status' => 0]);
        $chapter_total = 0;
        $count_words = 0;
        foreach ($chapters as $key => $chapter) {
            $chapter_num = $key + 1;
            $chapter['book_id'] = $book_id;
            $chapter['num'] = $chapter_num;
            $chapter['status'] = 1;
            Chapter::updateOrCreate(
                ['book_id' => $book_id, 'num' => $chapter_num],
                $chapter
            );
            $chapter_total++;
            $count_words += $chapter['original_count_words'];
        }

        $book->chapter_total = $chapter_total;
        $book->count_words = $count_words;
        $book->save();

        unlink($file_path);

        return true;
    }
}
